﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit;

namespace LogoScriptIDE
{
    /// <summary>
    /// 代码行高亮器
    /// </summary>
    class CodeLineRenderer : IBackgroundRenderer
    {
        private TextEditor m_editor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="editor">与之关联的编辑器</param>
        public CodeLineRenderer(TextEditor editor)
        {
            m_editor = editor;
        }

        /// <summary>
        /// 获得该高亮器所在的层（固定为背景层）
        /// </summary>
        public KnownLayer Layer
        {
            get { return KnownLayer.Background; }
        }

        /// <summary>
        /// 绘制回调函数
        /// </summary>
        public void Draw(TextView textView, DrawingContext drawingContext)
        {
            if (m_editor.Document == null)
                return;

            textView.EnsureVisualLines();

            // 对于每行不同的设置分别进行绘制
            foreach (var setting in RenderSettings)
            {
                var currentLine = m_editor.Document.GetLineByNumber(setting.LineNumber);

                // 绘制背景
                foreach (var rect in BackgroundGeometryBuilder.GetRectsForSegment(textView, currentLine))
                {
                    double drawingWidth = textView.ScrollOffset.X + textView.ActualWidth;
                    drawingContext.DrawRectangle(
                        new SolidColorBrush(setting.BgColor), null,
                        new Rect(rect.Location, new Size(drawingWidth, rect.Height)));
                }
            }
        }

        /// <summary>
        /// 背景行设置
        /// </summary>
        public struct Setting
        {
            /// <summary>
            /// 构造函数
            /// </summary>
            /// <param name="lineNumber">行号</param>
            /// <param name="bgColor">背景色</param>
            public Setting (int lineNumber, Color bgColor)
            {
                LineNumber = lineNumber;
                BgColor = bgColor;
            }

            /// <summary>
            /// 行号
            /// </summary>
            public int LineNumber;

            /// <summary>
            /// 背景色
            /// </summary>
            public Color BgColor;
        }

        private ICollection<Setting> m_renderSettings = new HashSet<Setting>();
        /// <summary>
        /// 获取背景行设置容器
        /// </summary>
        public ICollection<Setting> RenderSettings
        {
            get { return m_renderSettings; }
        }
    }
}
